﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Xml;
using SaaS;
using System.Collections.Generic;

namespace SaaS
{
    /// <summary>
    /// Summary description for AddItemService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class AddItemService : System.Web.Services.WebService
    {
        private List<string> parse(string values)
        {
            int pos, pos2;
            pos2 = -1;
            List<string> v = new List<string>();
            pos = values.IndexOf("|");
            while (pos >= 0)
            {
                v.Add(values.Substring(pos2 + 1, pos - pos2 - 1));
                pos2 = pos;
                pos = values.IndexOf("|", pos + 1);
            }
            v.Add(values.Substring(pos2 + 1, values.Length - pos2 - 1));
            return v;
        }

        [WebMethod]
        public string finish(string values)
        {
            List<string> v = parse(values);
            if (v.Count != 5)
                return "Arguments not equal to 5";
            XmlDocument xmldoc = new XmlDocument(); string tableDescription; string loginID; int tableID; string tableName;
            xmldoc.LoadXml(v[0]);
            tableDescription = v[1];
            loginID = v[2];
            tableID = Convert.ToInt32(v[3]);
            tableName = v[4];
            return finish( xmldoc,  tableDescription,  loginID, tableID,  tableName);
        }

        [WebMethod]
        public string finish(XmlDocument xmldoc, string tableDescription, string loginID,int tableID, string tableName)
        {
            XmlDocument xmltemp = new XmlDocument();
            xmltemp.LoadXml("<columns></columns>");
            xmltemp.DocumentElement.InnerXml = xmldoc.DocumentElement.InnerXml;
            //*********************************************
            // Send to DataBase
            // 
            String colString = xmltemp.OuterXml;
            //open database connection
            MiniSaaSDB db = new MiniSaaSDB();
            db.open();
            if (db.isOpen())
            {
                System.Data.SqlClient.SqlDataReader reader;
                int count = xmldoc.DocumentElement.ChildNodes.Count;
                int id;
                int ver;
                int rows;
                String tenantID = loginID;
                //String tenantID = "4";
                if (tableID > 0)
                {
                    //edit
                    id = tableID;
                    reader = db.executeQuery("SELECT MAX(Table_Version)+1 FROM META WHERE Table_ID = " + tableID.ToString());
                    if (!reader.HasRows)
                        ver = 1;
                    else
                    {
                        reader.Read();
                        ver = (int)reader[0];
                    }
                }
                else
                {
                    //create new
                    ver = 1;
                    reader = db.executeQuery("SELECT MAX(Table_ID)+1 FROM META");
                    if (!reader.HasRows)
                        id = 1;
                    else
                    {
                        reader.Read();
                        id = (int)reader[0];
                    }
                }
                reader.Close();
                String query;
                query = "INSERT INTO META (Table_ID, Table_Version, Login_ID, " +
                    "Table_Name, Table_Columns_Count, Table_Columns, Table_Description) " +
                    "VALUES (" + id.ToString() + ", " + ver.ToString() + ", " + tenantID.ToString() + ", '" + tableName + "', " +
                    count.ToString() + ", '" + colString + "', ";
                if (tableDescription != null && tableDescription.Length > 0)
                    query = query + "'" + tableDescription + "');";
                else
                    query = query + "NULL);";
                rows = db.executeNonQuery(query);
                if (rows <= 0)
                {
                    //No rows affected
                    db.close();
                    return "No rows affected";
                }
                db.close();
            }
            else
            {
                //Error opening DB
                return "Error opening database.";
            }
            return "";
        }
        [WebMethod]
        public XmlDocument addAttribute(string values)
        {
            List<string> v = parse(values);
            if (v.Count != 7)
                return null;
            XmlDocument currentDoc = new XmlDocument(); string name; string type;
            bool allowNull; string defaultVal; int colID; bool isKey;
            currentDoc.LoadXml(v[0]);
            name = v[1];
            type = v[2];
            allowNull = Convert.ToBoolean(v[3]);
            defaultVal = v[4];
            colID = Convert.ToInt32(v[5]);
            isKey = Convert.ToBoolean(v[6]);
            return addAttribute( currentDoc,  name,  type,
             allowNull,  defaultVal,  colID,  isKey);
        }
        [WebMethod]
        public XmlDocument addAttribute(XmlDocument currentDoc, string name, string type,
            bool allowNull, string defaultVal, int colID, bool isKey)
        {
            //Create a new node
            XmlElement col = currentDoc.CreateElement("col");
            XmlElement xmlAtr = currentDoc.CreateElement("name");
            XmlElement xmlType = currentDoc.CreateElement("type");
            XmlElement xmlAllowNull = currentDoc.CreateElement("allownull");
            XmlElement xmlD = currentDoc.CreateElement("default");
            XmlElement columnID = currentDoc.CreateElement("columnID");
            XmlElement xmlPK = currentDoc.CreateElement("priKey");
            XmlElement xmlFK = currentDoc.CreateElement("foreign");
            XmlElement xmlFKID = currentDoc.CreateElement("foreignTableID");
            XmlElement xmlFKCol = currentDoc.CreateElement("foreignCol");

            columnID.InnerText = colID.ToString();
            xmlAtr.InnerText = name;
            xmlType.InnerText = type;
            xmlAllowNull.InnerText = allowNull ? "True" : "False";
            xmlD.InnerText = defaultVal;
            xmlPK.InnerText = isKey ? "True" : "False";

            col.AppendChild(xmlAtr);
            col.AppendChild(xmlType);
            col.AppendChild(xmlAllowNull);
            col.AppendChild(xmlD);
            col.AppendChild(columnID);
            col.AppendChild(xmlPK);
            col.AppendChild(xmlFK);
            xmlFK.AppendChild(xmlFKID);
            xmlFK.AppendChild(xmlFKCol);
            currentDoc.DocumentElement.AppendChild(col);

            return currentDoc;
        }
    }
}
